package sweetvsti;

import java.awt.Dimension;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 *
 * @author uimac
 */
public final class Util {

    private static JComponent parent = null;

    public static void openMessageDialog(String mes) {
        JOptionPane.showMessageDialog(
                parent, mes, "about", JOptionPane.INFORMATION_MESSAGE);
    }

    public static void openTextDialog(String str) {
        Dimension size = new Dimension(350, 350);
        JTextArea textArea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(textArea);

        textArea.setLineWrap(true);
        textArea.setText(str);
        scrollPane.setPreferredSize(size);
        JOptionPane.showMessageDialog(
                parent, scrollPane, "please copy to use", JOptionPane.INFORMATION_MESSAGE);
    }

    public static File openFolderChooser() {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = chooser.showOpenDialog(parent);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            return chooser.getSelectedFile();
        }
        return null;
    }

    public static File openFileChooser() {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int returnVal = chooser.showOpenDialog(parent);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            return chooser.getSelectedFile();
        }
        return null;
    }
    
    // 128鍵盤の周波数テーブル作成
    public static void makeFrequencyTable(double[] freq_table) {
        // 2の(1/12)乗
        double deltaFreq = 1.059463094359;
        double a = 13.75; // a
        a *= deltaFreq;	// b
        a *= deltaFreq;	// bb
        a *= deltaFreq;	// c, MIDIで一番低いC
        for (int i = 0; i < freq_table.length; i++) {
            freq_table[i] = a;
            a *= deltaFreq;
        }
    }
    
    public static boolean duplicateWaveFile(File input, File outputdir, int basetune, int duration)
    {
        double seconds = 1.0;
        if (duration == 240) {
            seconds = 0.25;
        } else if (duration == 480) {
            seconds = 0.5;
        } else {
            // 未対応
            return false;
        }
        
        AudioInputStream instream = null;
        try {
            if (input.exists())
            {
                instream = AudioSystem.getAudioInputStream(input);
                AudioFormat format = instream.getFormat();
                
                //int readSize = instream.available();
                int sampleSize = (int) (format.getFrameSize() * format.getFrameRate() * seconds);
                byte[] buffer = new byte[sampleSize];
                
                
                if (buffer.length != sampleSize) {
                    buffer = new byte[sampleSize];
                }
                
                int readBytesSum = 0;
                int counter = 0;
                int keyCounter = 0;
                int charaCounter = 0;
                instream.skip(sampleSize * 2 * 8);
                for (int readBytes = instream.read(buffer, 0, sampleSize);
                        readBytes >= 0;
                        readBytes = instream.read(buffer, 0, sampleSize))
                {
                    readBytesSum += readBytes;
                    if (readBytesSum >= sampleSize) {
                        InputStream in = new ByteArrayInputStream(buffer);
                        AudioInputStream outstream = new AudioInputStream(in, format, readBytesSum);
                        try {
                            ++charaCounter;
                            if (charaCounter >= Settings.instance().getCHARACTERS())
                            {
                                charaCounter = 1;
                                
                                ++keyCounter; 
                                if (keyCounter >= 12) {
                                    ++basetune;
                                    keyCounter = 0;
                                }
                            }
                            Map map = Settings.instance().getKanaMap();
                            String fileName = Integer.toString(duration) + "_" + Integer.toString((basetune+2)*12 + keyCounter) + "_" + Integer.toString(charaCounter);
                            File out = new File(outputdir.getAbsolutePath() + File.separator + fileName + ".wav");
                            AudioSystem.write(outstream, AudioFileFormat.Type.WAVE, out);
                            
                        } catch (IOException e) {
                            System.out.println(e);
                        }
                        
                        ++counter;
                        readBytesSum = 0;
                    }
                }
                
                return true;
            }
        } catch (Exception ex) {
            if (instream != null) {
                try {
                    instream.close();
                    instream = null;
                } catch (Exception exx) {
                }
            }
        } finally {
            if (instream != null) {
                try {
                    instream.close();
                    instream = null;
                } catch (Exception exx) {
                }
            }
        }
        return false;
    }
}
